<?php

//require_once LIBRARIES_ENTITIES_DATABASE;
//require_once LIBRARIES_TOOLS_UTILITY;
//require_once LIBRARIES_TOOLS_XTEMPLATE;
//require_once LIBRARIES_ENTITIES_ITEMPROPERTIES;
//require_once LIBRARIES_ENTITIES_ITEMS;

class Controller {

    public function invoke() {

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }


        // CHECK ACTION
        // addToCart action
        if ($action == 'addToCart') {

            // item ID
            $itemID = $_POST['hdItemID'];

            // item object
            $item = $this->getItemByID($itemID);


            // item price
            $itemPrice = $item->getPrice();

            // quantity
            $quantity = 1;
            if (isset($_POST['txtQuantity'])) {
                $quantity = $_POST['txtQuantity'];
            }

            // total price of an item
            $totalPrice = $itemPrice * $quantity;


            // string of property
            $strProperty = '';
            if (isset($_POST['hdItemProperties'])) {
                $strProperty = $_POST['hdItemProperties'];
            }


            // array of property
            $arrayProperty = array();


            if ($strProperty != '') {
                // convert string to array of property

                $properties = array();

                $properties = explode(',', $strProperty);

                for ($i = 0; $i < count($properties); $i++) {
                    //property id
                    $arrayProperty[$i][0] = $properties[$i];
                    // is already
                    $arrayProperty[$i][1] = '';
                }
            }

            // if exist 'cart session'
            if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {

                $isAlready = false;

                // UPDATE QUANTITY IF EXIST ITEM
                // ELSE ADD AN ITEM TO ARRAY
                for ($i = 0; $i < count($_SESSION['cart']); $i++) {
                    // if exist array property
                    if (count($arrayProperty) > 0) {
                        // loop each property and check the existence of the item (with property) in cart
                        // if exist then increase quantity
                        for ($y = 0; $y < count($arrayProperty); $y++) {
                            // loop each item in cart to check already
                            if ($_SESSION['cart'][$i]['itemID'] == $itemID && $_SESSION['cart'][$i]['propertyID'] == $arrayProperty[$y][0]) {
                                $_SESSION['cart'][$i]['quantity'] = $_SESSION['cart'][$i]['quantity'] + $quantity;
                                $_SESSION['cart'][$i]['totalEachItem'] = $_SESSION['cart'][$i]['totalEachItem'] + $totalPrice;
                                // is already
                                $arrayProperty[$y][1] = 1;
                            }
                        }
                    } else {
                        // if exist the item
                        if ($_SESSION['cart'][$i]['itemID'] == $itemID && $_SESSION['cart'][$i]['propertyID'] == '') {
                            $_SESSION['cart'][$i]['quantity'] = $_SESSION['cart'][$i]['quantity'] + $quantity;
                            $_SESSION['cart'][$i]['totalEachItem'] = $_SESSION['cart'][$i]['totalEachItem'] + $totalPrice;
                            $isAlready = true;
                            break;
                        }
                    }
                }

                if (count($arrayProperty) > 0) {
                    // loop each property then add new item into cart if not exist
                    for ($y = 0; $y < count($arrayProperty); $y++) {
                        if ($arrayProperty[$y][1] != 1) {
                            $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => $arrayProperty[$y][0], 'itemPrice' => $itemPrice);
                        }
                    }
                } else if ($isAlready == false) {
                    $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => '', 'itemPrice' => $itemPrice);
                }
            } else {
                // if exist array property
                if (count($arrayProperty) > 0) {
                    // each property corresponding to one product
                    for ($i = 0; $i < count($arrayProperty); $i++) {
                        $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => $arrayProperty[$i][0], 'itemPrice' => $itemPrice);
                    }
                } else {
                    $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => '', 'itemPrice' => $itemPrice);
                }
            }
        }
        // destroy action
        else if ($action == 'destroy') {
            unset($_SESSION['cart']);
        }
        // remove item action
        else if ($action == 'removeItem') {

            // item ID
            $itemID = $_POST['hdItemID'];

            // loop each item, if the item equal checked item then remove it from array
            for ($i = 0; $i < count($_SESSION['cart']); $i++) {
                if ($_SESSION['cart'][$i]['itemID'] == $itemID) {
                    unset($_SESSION['cart'][$i]);
                }
            }

            // sort associative arrays in ascending order, according to the key            
            ksort($_SESSION['cart']);

            //  reindexed from zero
            $_SESSION['cart'] = array_values($_SESSION['cart']);

            echo 'OK';
            exit();
        }
        // minus quantity action
        else if ($action == 'minus') {

            // item ID
            $itemID = $_POST['hdItemID'];

            // loop each item, if the item equal checked item then remove it from array
            for ($i = 0; $i < count($_SESSION['cart']); $i++) {
                if ($_SESSION['cart'][$i]['itemID'] == $itemID) {
                    if ($_SESSION['cart'][$i]['quantity'] > 1) {

                        // minus quantity by 1
                        $_SESSION['cart'][$i]['quantity'] = $_SESSION['cart'][$i]['quantity'] - 1;

                        // calculate total each item
                        $_SESSION['cart'][$i]['totalEachItem'] = $_SESSION['cart'][$i]['quantity'] * $_SESSION['cart'][$i]['itemPrice'];
                    }
                }
            }
            echo 'OK';
            exit();
        }
        // plus quantity action
        else if ($action == 'plus') {

            // item ID
            $itemID = $_POST['hdItemID'];

            // loop each item, if the item equal checked item then remove it from array
            for ($i = 0; $i < count($_SESSION['cart']); $i++) {
                if ($_SESSION['cart'][$i]['itemID'] == $itemID) {
                    // minus quantity by 1
                    $_SESSION['cart'][$i]['quantity'] = $_SESSION['cart'][$i]['quantity'] + 1;

                    // calculate total each item
                    $_SESSION['cart'][$i]['totalEachItem'] = $_SESSION['cart'][$i]['quantity'] * $_SESSION['cart'][$i]['itemPrice'];
                }
            }
            echo 'OK';
            exit();
        } else if ($action == 'loadList') {

            require_once '../../constant.php';
            require_once LIBRARIES_ENTITIES_DATABASE;
            require_once LIBRARIES_TOOLS_UTILITY;
            require_once LIBRARIES_TOOLS_XTEMPLATE;
            require_once LIBRARIES_ENTITIES_ITEMPROPERTIES;
            require_once LIBRARIES_ENTITIES_ITEMS;

            $derectory = dirname(__FILE__);
            $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'cart.html');

            session_start();


            if (isset($_SESSION['cart']) && (count($_SESSION['cart']) > 0)) {
                
                $total = 0;

                foreach ($_SESSION['cart'] as $item) {

                    if ($item['propertyID'] != '') {
                        // item property object
                        $itemProperty = $this->getItemPropertyByID($item['propertyID']);
                        $xtemplate->assign('ITEM_PROPERTY_VALUE', $itemProperty->getValue());
                    } else {
                        $xtemplate->assign('ITEM_PROPERTY_VALUE', '');
                    }

                    // item object 
                    $itemObj = $this->getItemByID($item['itemID']);

                    $xtemplate->assign('ITEM_ID', $item['itemID']);
                    $xtemplate->assign('ITEM_NAME', $itemObj->getName());
                    $xtemplate->assign('ITEM_IMAGE', $itemObj->getImage());
                    $xtemplate->assign('ITEM_PRICE', Utility::formatToCurrencyString($item['itemPrice']));
                    $xtemplate->assign('ITEM_QUANTITY', $item['quantity']);
                    $xtemplate->assign('TOTAL_EACH_ITEM', Utility::formatToCurrencyString($item['totalEachItem']));

                    // calculate total
                    $total = $total + $item['totalEachItem'];

                    $xtemplate->parse('main.item_table.list');
                }

                $xtemplate->assign('TOTAL', Utility::formatToCurrencyString($total));

                
                // nếu có danh sách thì mới hiển thị nút huỷ đơn hàng và nút thanh toán
                $xtemplate->parse('main.item_table.action_button');
            }

            $xtemplate->parse('main.item_table');
            $xtemplate->parse('main');
            $xtemplate->out('main');
            exit();
        }










        $derectory = dirname(__FILE__);
        $xtemplate = new XTemplate($derectory . DS . 'views' . DS . 'cart.html');

        $xtemplate->parse('main.layout');
        $xtemplate->parse('main.javascript');
        $xtemplate->parse('main');
        $xtemplate->out('main');
        
        
        
    }

    // get an item_property by item property ID
    private function getItemPropertyByID($itemPropertyID) {
        $db = new Database();
        try {
            $itemProperty = new ItemProperties();
            $itemProperty->setID($itemPropertyID);
            $result = $itemProperty->getItemPropertyByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

    // get item detail by item ID
    private function getItemByID($itemID) {
        $db = new Database();
        try {
            $item = new Items();
            $item->setID($itemID);
            $result = $item->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

}

?>
